package com.yaolonga.dc.exector.mybatisplus;

import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yaolonga.dc.core.*;
import com.yaolonga.dc.core.exception.NodeExecuteException;
import com.yaolonga.dc.core.spi.NodeExecutor;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @author yaolong
 * @version V1.0.0
 * @program dynamic-condition
 * @description 默认的节点执行器
 * @create 2024-06-02 21:13
 **/
@Slf4j
public class MybatisPlusNodeExecutor implements NodeExecutor<QueryChainWrapper> {

    NodeParser<QueryChainWrapper> nodeParser;

    @Override
    public NodeParser<QueryChainWrapper> nodeParser() {
        if (nodeParser != null){
            return nodeParser;
        }
        return (nodeParser = new MybatisPlusNodeParser());
    }

    @Override
    public <T> List<T> execute(List<GroupNode> astNode, Class<T> bean) {
        try {
            QueryChainWrapper<T> parse = nodeParser().parse(astNode, bean);
            return parse.list();
        }catch (Exception e){
            log.error("MybatisPlusNodeExecutor 执行异常: {}",e.getMessage(),e);
            throw new NodeExecuteException("MybatisPlusNodeExecutor 执行异常: ",e);
        }
    }



    @Override
    public <T> DCPage<T> executePage(int page, int pageSize, List<GroupNode> astNode, Class<T> bean) {
        try {
            QueryChainWrapper<T> parse = nodeParser().parse(astNode, bean);
            Page<T> page1 = parse.page(new Page<>(page, pageSize));
            DCPage<T> p = new DCPage<>();
            p.setData(page1.getRecords());
            p.setTotal(page1.getTotal());
            p.setPage(page);
            p.setPageSize(pageSize);
            p.setTotalPage(page1.getPages());
            return p;
        }catch (Exception e){
            log.error("MybatisPlusNodeExecutor 执行异常: {}",e.getMessage(),e);
            throw new NodeExecuteException("MybatisPlusNodeExecutor 执行异常: ",e);

        }
    }



    @Override
    public ExecutorType getExecutorType() {
        return DefaultExecutorType.mybatis_plus;
    }
}
